﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter21.Code02.Example05
{
    using System.IO;

    public class CommaValues
    {
        public static List<Dictionary<string, string>> GetData(out List<string> columns)
        {
            string line;
            string[] stringArray;
            char[] charArray = new char[] { ',' };
            List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
            columns = new List<string>();
            try
            {
                FileStream aFile = new FileStream("SomeData.txt", FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
                line = sr.ReadLine();
                stringArray = line.Split(charArray);
                for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
                {
                    columns.Add(stringArray[x]);
                }
                line = sr.ReadLine();
                while (line != null)
                {
                    stringArray = line.Split(charArray);
                    Dictionary<string, string> dataRow = new Dictionary<string, string>();
                    for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
                    {
                        dataRow.Add(columns[x], stringArray[x]);
                    }
                    data.Add(dataRow);
                    line = sr.ReadLine();
                }
                sr.Close();
                aFile.Close();
                return data;
            }
            catch (IOException e)
            {
                Console.WriteLine("An exception has been thrown!");
                Console.WriteLine(e.ToString());
                return data;
            }
        }
    }
}
